package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.dao.SetmealMapper;
import com.itheima.reggie.domian.Setmeal;
import com.itheima.reggie.domian.SetmealDish;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class SetmealImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //1把套餐存进数据库
        this.save(setmealDto);
        //2把关系表存进数据库
        //得到客户端传递的每一个菜品表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);
    }


    @Override
    @Transactional
    public void deletes(Long[] ids) {
        //0判断套餐状态是否停售    0停用  1启用
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId, Arrays.asList(ids));
        wrapper.in(Setmeal ::getStatus,1);
        //查询套餐表集合
        int count = this.count(wrapper);
        if (count > 0){
            throw new CustomerException("套餐正在售卖");
        }
        //1删除套餐表setmeal
        this.removeByIds(Arrays.asList(ids));
        //2删除套餐对应菜品表setmeal_dish
        LambdaQueryWrapper<SetmealDish> wrap = new LambdaQueryWrapper<>();
        wrap.in(SetmealDish ::getSetmealId, Arrays.asList(ids));
        setmealDishService.remove(wrap);
    }
}
